package com.zhongmai.yzfgrabanorder.netty_lib;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.widget.Toast;


import com.zhongmai.yzfgrabanorder.fragment.FragmentsManager;
import com.zhongmai.yzfgrabanorder.fragment.GrabAnOrderFragment;
import com.zhongmai.yzfgrabanorder.netty_lib.bean.ChatInfo;
import com.zhongmai.yzfgrabanorder.netty_lib.bean.NettyBaseFeed;
import com.zhongmai.yzfgrabanorder.netty_lib.netty.NettyClient;
import com.zhongmai.yzfgrabanorder.netty_lib.netty.NettyListener;
import com.zhongmai.yzfgrabanorder.utils.Constants;

import java.util.Stack;


/**
 * 长连接服务
 */
public class NettyService extends Service implements NettyListener {

    private NetworkReceiver receiver;
    public static final String TAG = NettyService.class.getName();

    public NettyService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onCreate() {
        super.onCreate();
        receiver = new NetworkReceiver();
        IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        LocalBroadcastManager.getInstance(this).registerReceiver(receiver, filter);

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        NettyClient.getInstance().setReconnectNum(3);
        NettyClient.getInstance().setListener(this);
        connect();
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);
        NettyClient.getInstance().setReconnectNum(0);
        NettyClient.getInstance().disconnect();
    }

    private void connect() {
        if (!NettyClient.getInstance().getConnectStatus()) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    NettyClient.getInstance().connect();//连接服务器
                }
            }).start();
        }
    }

    @Override
    public void onMessageResponse(String messageHolder) {
        if (messageHolder.contains("用户上线成功")) {
            Constants.online = true;
            Stack<GrabAnOrderFragment> fragments = FragmentsManager.getInstance().getFragments();
            for (GrabAnOrderFragment fragment : fragments) {
                if (fragment == null || !fragment.isVisible()) {
                    continue;
                }
                Message message = Message.obtain();
                message.what = 0;
                fragment.getHandler().sendMessage(message);
            }
        }else if(messageHolder.contains("用户上线失败")){
            Constants.online = false;
            Stack<GrabAnOrderFragment> fragments = FragmentsManager.getInstance().getFragments();
            for (GrabAnOrderFragment fragment : fragments) {
                if (fragment == null || !fragment.isVisible()) {
                    continue;
                }
                Message message = Message.obtain();
                message.what = 2;
                fragment.getHandler().sendMessage(message);
            }
        }
    }

    /**
     * 状态改变触发
     *
     * @param statusCode
     */
    @Override
    public void onServiceStatusConnectChanged(final int statusCode) {
        if (statusCode == NettyListener.STATUS_CONNECT_SUCCESS) {
            Log.e(TAG, "connect sucessful");
            sendAuthor();
        } else {
            Log.e(TAG, "connect fail statusCode = " + statusCode);
            Handler handlerThree = new Handler(Looper.getMainLooper());
            handlerThree.post(new Runnable() {
                public void run() {
                    if (statusCode == NettyListener.STATUS_CONNECT_ERROR) {
                        Toast.makeText(getApplicationContext(), "服务器连接失败", Toast.LENGTH_LONG).show();
                    }
                }
            });
            Stack<GrabAnOrderFragment> fragments = FragmentsManager.getInstance().getFragments();
            for (GrabAnOrderFragment fragment : fragments) {
                if (fragment == null || !fragment.isVisible()) {
                    continue;
                }
                Message message = Message.obtain();
                message.what = 1;
                fragment.getHandler().sendMessage(message);
            }
        }

    }

    /**
     * 发送认证信息
     */
    private void sendAuthor() {
        final NettyBaseFeed<ChatInfo> baseFeed = new NettyBaseFeed<>();
        baseFeed.setCmd("register");
        baseFeed.setMessage("登录");
        final ChatInfo chatInfo = new ChatInfo();
        chatInfo.setUser(Constants.user);
        baseFeed.setData(chatInfo);
        NettyClient.getInstance().sendMessage(baseFeed, null);
    }

    public class NetworkReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
            if (activeNetwork != null) { // connected to the internet
                if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI
                        || activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
                    connect();
                    Log.e(TAG, "connecting ...");
                }
            }
        }
    }
}
